<template>
    <div>
        <div class="demo-input-size">
            <el-button type="primary" style="margin: 4px 0;" @click="showAdminModal">添加管理员</el-button>
            <el-input v-model.trim="keywords" class="w-50 m-2" placeholder="请输入关键字" :suffix-icon="Search" />
        </div>

        <!-- 表格 -->
        <el-table :data="filterAdminData().slice((currentPage - 1) * pageSize, currentPage * pageSize)" style="width: 100%">
            <el-table-column label="选择" type="index" width="100">
                <el-checkbox v-model="checked" size="large" />
            </el-table-column>
            <el-table-column label="序号" type="index" width="100" />
            <el-table-column label="管理员" prop="adminUser" width="180" />
            <el-table-column label="角色" prop="role" width="180">
                <template #default="scope">
                    <el-tag v-if="(scope.row.role === 1)">超级管理员</el-tag>
                    <el-tag type="success" v-else>管理员</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-popconfirm title="确定删除吗?" @confirm="removeAdmin(scope.row._id)" confirm-button-text="确定" cancel-button-text="再想想">
                        <template #reference>
                            <el-button type="danger" :icon="Delete" circle>
                            </el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination style="float: right; margin-top: 10px;" v-model:current-page="currentPage"
            v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]" :background="background"
            layout="total, sizes, prev, pager, next, jumper" :total="filterAdminData().length"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        <el-dialog v-model="showModal" title="添加管理员" width="30%">
            <el-form ref="ruleFormRef" :model="ruleForm" status-icon label-width="120px" class="demo-ruleForm">
                <el-form-item label="名称" prop="adminUser">
                    <el-input v-model="ruleForm.adminUser" type="text" autocomplete="off" />
                </el-form-item>
                <el-form-item label="密码" prop="adminPass">
                    <el-input v-model="ruleForm.adminPass" type="password" autocomplete="off" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                    <el-button @click="resetForm">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import {
    Delete,
    Edit,
    Search
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus'
import { getAdminList, addAdmin, delAdmin } from '../../api/api';


const checked = ref(false)
const keywords = ref('')

// 表格的接口数据约束
interface User {
    _id: string
    adminUser: string
    adminPass: string
    role: string
}

const currentPage = ref(1)
const pageSize = ref(10)
const background = ref(true)

// 添加修改弹出框显示状态
const showModal = ref(false)


// 每页显示个数
const handleSizeChange = (val: number) => {
    pageSize.value = val
}
// 页码
const handleCurrentChange = (val: number) => {
    currentPage.value = val
}

// 添加管理员
const showAdminModal = () => {
    showModal.value = true
}

// 删除管理员
const removeAdmin = async (id: string) => {
    console.log(123,id)
    let res = await delAdmin({ id, })
    console.log(222,res);
    
    if (res.data.errorCode === 0) {
        ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 1500
        })
        getAdminData()
    } else {
        ElMessage({
            message: '删除失败！',
            type: 'error',
            duration: 1500
        })
    }
}

// 修改管理员
// const updateAdmin = (index: number, row: User) => {
//     console.log(index, row);

// }

// 表格数据
const adminData = ref<User[]>([])

// 过滤后表格数据
const filterAdminData = () => {
    return adminData.value.filter((item: User) => {
        return item.adminUser.includes(keywords.value)
    })
}

onMounted(() => {
    getAdminData()
})

// 获取管理员数据
const getAdminData = async () => {
    let res = await getAdminList()
    console.log(res);
    adminData.value = res.data.data
}


// Modal表单部分
const ruleFormRef = ref<FormInstance>()

// const validatePass = (rule: any, value: any, callback: any) => {
//   if (value === '') {
//     callback(new Error('Please input the password'))
//   } else {
//     if (ruleForm.checkPass !== '') {
//       if (!ruleFormRef.value) return
//       ruleFormRef.value.validateField('checkPass', () => null)
//     }
//     callback()
//   }
// }

const ruleForm = reactive({
    adminUser: '',
    adminPass: ''
})

// const rules = reactive({
//   pass: [{ validator: validatePass, trigger: 'blur' }],
//   checkPass: [{ validator: validatePass2, trigger: 'blur' }],
//   age: [{ validator: checkAge, trigger: 'blur' }],
// })

const submitForm = async () => {
    console.log(ruleForm);
    let res = await addAdmin({
        adminUser: ruleForm.adminUser,
        adminPass: ruleForm.adminPass
    })
    console.log(res);
    if (res.data.errorCode === 0) {
        ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 1500
        })
        ruleForm.adminUser = ''
        ruleForm.adminPass = ''
        showModal.value = false
        getAdminData()
    } else if (res.data.errorCode === 1) {
        ElMessage({
            message: res.data.message,
            type: 'error'
        })
    }
}

const resetForm = () => {
    ruleForm.adminUser = ''
    ruleForm.adminPass = ''
    showModal.value = false
}
</script>

<style lang="scss" scoped>
.el-button {
    margin-bottom: 10px;
}

.w-50 {
    width: 300px;
    margin-left: 20px;
}
</style>